﻿@page "/Form2"
@using System.Diagnostics.CodeAnalysis
@using BootstrapBlazor.OnlyServerZhongShun.Data.dbmodels
@using System.Data
@inject ILogger<Form2> NormalLogger
@inject AuthenticationStateProvider authenticationStateProvider
@inject ToastService ToastService
@inject IConfiguration _congifuration
@inject SqlSugarScope _SqlSugarScope
@attribute [Authorize(Roles = "超级管理员,业务总, 业务经理, 业务员")]
<style>
    .multi-select {
        --bb-multi-select-min-height: 26px;
    }
</style>

<div class="row g-1">
    <div class="col-6">
        <BootstrapInputGroup>
            <BootstrapInputGroupLabel DisplayText="查询日期" />
            <DateTimeRange @bind-Value="@NormalDateTimeRangeValue" OnConfirm="OnNormalConfirm" ShowSidebar="true" ViewMode="DatePickerViewMode.Date" IsEditable="true" DateFormat="yyyy-MM-dd">
                <TimePickerSetting ShowClockScale="true" IsAutoSwitch="false" />
            </DateTimeRange>
        </BootstrapInputGroup>
    </div>
    <div class="col-3">
        <BootstrapInputGroup>
            <BootstrapInputGroupLabel DisplayText="客户" />
            <Select IsVirtualize="true" Items="客户列表Items" @bind-Value="选中客户" OnSearchTextChanged="OnSearchTextChanged" ShowSearch="true" IsClearable="true"></Select>
        </BootstrapInputGroup>
    </div>
    <div class="col-3">
        <BootstrapInputGroup>
            <BootstrapInputGroupLabel DisplayText="业务员" />
            <MultiSelect Items="@业务员Items" @bind-Value="@选中业务员List" OnSelectedItemsChanged="@业务员选择改变事件" ShowToolbar="true" />
        </BootstrapInputGroup>
    </div>
</div>

<div class="row g-1">
<div class="col-9 col-sm-6">
    <BootstrapInputGroup>
        <BootstrapInputGroupLabel DisplayText="部门" />
        <MultiSelect Items="@部门Items" @bind-Value="@选中部门List" OnSelectedItemsChanged="@部门选择改变事件" ShowToolbar="true" />
    </BootstrapInputGroup>
    </div>

        <div class="col-3">
        <BootstrapInputGroup>
            <BootstrapInputGroupLabel DisplayText="养殖类别" />
            <Select IsVirtualize="true" Items="养殖类别Items" @bind-Value="选中养殖类别" ShowSearch="false" IsClearable="true"></Select>
        </BootstrapInputGroup>
    </div>

    <div class="col-3 col-sm-3 col-md-3 col-lg-auto">
        <Button OnClick="@Button_chaxun_Click" IsAsync="true" Color="Color.Primary">查询</Button>
        <Button OnClick="@Button_daochu" Color="Color.Info">导出</Button>
    </div>
</div>
@* <div class="table-fixed-header"> *@
    <Table class="table" TItem="DynamicObject" DynamicContext="DataTableDynamicContext"
           IsBordered="true" IsMultipleSelect="false" ShowToolbar="true" ShowRefresh="false" ShowDefaultButtons="false" IsPagination="true" ShowExportButton="false"
           OnExportAsync="OnExportAsync" OnSort="OnSort" ShowFooter="true" IsStriped="true" PageItemsSource="new int[]{1000,2000,3000,4000,5000,10000}" TableSize="TableSize.Compact"
           Height="500" IsFixedHeader="true">
        <FooterTemplate>
            <tr>
                @if (DataTableDynamicContext != null && DataTableDynamicContext.DataTable.Rows.Count > 0)
                {
                    @foreach (DataColumn property in DataTableDynamicContext.DataTable.Columns)
                    {
                        <td>
                            @*  //如果不是 代理商名称,部门 列 *@
                            @* @if (property.ColumnName != "代理商名称" && property.ColumnName != "部门" && property.ColumnName != "销售员" && Type.GetTypeCode(property.DataType) == TypeCode.String) *@
                        @if (Type.GetTypeCode(property.DataType) != TypeCode.String && property.ColumnName != "本期回款率" && property.ColumnName != "同期回款率" && property.ColumnName != "回款率差异" && property.ColumnName != "销售差异率" && property.ColumnName != "序号")
                            {
                                //当前列的合计
                                var sum = DataTableDynamicContext.DataTable.AsEnumerable().Sum(dr =>
                                {
                                    if (dr.IsNull(property.ColumnName)) return 0m;
                                    object value = dr[property.ColumnName];
                                    if (value is int)
                                        return (decimal)(int)value;
                                    else if (value is decimal)
                                        return (decimal)value;
                                    else
                                        return 0m;
                                });
                                @sum
                            }
                            else if (property.ColumnName == "本期回款率")
                            {
                                var sum1 = DataTableDynamicContext.DataTable.AsEnumerable().Sum(dr =>
                                {
                                    if (dr.IsNull("本期回款额")) return 0m;
                                    object value = dr["本期回款额"];
                                    if (value is int)
                                        return (decimal)(int)value;
                                    else if (value is decimal)
                                        return (decimal)value;
                                    else
                                        return 0m;
                                });

                                var sum2 = DataTableDynamicContext.DataTable.AsEnumerable().Sum(dr =>
                                {
                                    if (dr.IsNull("本期销售额")) return 0m;
                                    object value = dr["本期销售额"];
                                    if (value is int)
                                        return (decimal)(int)value;
                                    else if (value is decimal)
                                        return (decimal)value;
                                    else
                                        return 0m;
                                });
                                if (sum2 > 0)
                                {
                                    @((sum1 / sum2).ToString("p2"))
                                }
                                
                            }
                        else if (property.ColumnName == "销售差异率")
                        {
                            var sum1 = DataTableDynamicContext.DataTable.AsEnumerable().Sum(dr =>
                            {
                                if (dr.IsNull("销售差异")) return 0m;
                                object value = dr["销售差异"];
                                if (value is int)
                                    return (decimal)(int)value;
                                else if (value is decimal)
                                    return (decimal)value;
                                else
                                    return 0m;
                            });

                            var sum2 = DataTableDynamicContext.DataTable.AsEnumerable().Sum(dr =>
                            {
                                if (dr.IsNull("同期销售额")) return 0m;
                                object value = dr["同期销售额"];
                                if (value is int)
                                    return (decimal)(int)value;
                                else if (value is decimal)
                                    return (decimal)value;
                                else
                                    return 0m;
                            });
                            if (sum2 > 0)
                            {
                                @((sum1 / sum2).ToString("p2"))
                            }

                        }
                            else if (property.ColumnName == "同期回款率")
                            {
                                var sum1 = DataTableDynamicContext.DataTable.AsEnumerable().Sum(dr =>
                                {
                                    if (dr.IsNull("同期回款额")) return 0m;
                                    object value = dr["同期回款额"];
                                    if (value is int)
                                        return (decimal)(int)value;
                                    else if (value is decimal)
                                        return (decimal)value;
                                    else
                                        return 0m;
                                });

                                var sum2 = DataTableDynamicContext.DataTable.AsEnumerable().Sum(dr =>
                                {
                                    if (dr.IsNull("同期销售额")) return 0m;
                                    object value = dr["同期销售额"];
                                    if (value is int)
                                        return (decimal)(int)value;
                                    else if (value is decimal)
                                        return (decimal)value;
                                    else
                                        return 0m;
                                });
                                if (sum2 > 0)
                                {
                                    @((sum1 / sum2).ToString("p2"))
                                }
                               
                            }
                            else if (property.ColumnName == "回款率差异")
                            {
                                var sum1 = DataTableDynamicContext.DataTable.AsEnumerable().Sum(dr =>
                                {
                                    if (dr.IsNull("同期回款额")) return 0m;
                                    object value = dr["同期回款额"];
                                    if (value is int)
                                        return (decimal)(int)value;
                                    else if (value is decimal)
                                        return (decimal)value;
                                    else
                                        return 0m;
                                });

                                var sum2 = DataTableDynamicContext.DataTable.AsEnumerable().Sum(dr =>
                                {
                                    if (dr.IsNull("同期销售额")) return 0m;
                                    object value = dr["同期销售额"];
                                    if (value is int)
                                        return (decimal)(int)value;
                                    else if (value is decimal)
                                        return (decimal)value;
                                    else
                                        return 0m;
                                });
                                decimal 同期回款率 = 0;
                                if (sum2 > 0)
                                {
                                    同期回款率 = sum1 / sum2;
                                }

                                var sum3 = DataTableDynamicContext.DataTable.AsEnumerable().Sum(dr =>
                                {
                                    if (dr.IsNull("本期回款额")) return 0m;
                                    object value = dr["本期回款额"];
                                    if (value is int)
                                        return (decimal)(int)value;
                                    else if (value is decimal)
                                        return (decimal)value;
                                    else
                                        return 0m;
                                });

                                var sum4 = DataTableDynamicContext.DataTable.AsEnumerable().Sum(dr =>
                                {
                                    if (dr.IsNull("本期销售额")) return 0m;
                                    object value = dr["本期销售额"];
                                    if (value is int)
                                        return (decimal)(int)value;
                                    else if (value is decimal)
                                        return (decimal)value;
                                    else
                                        return 0m;
                                });
                                decimal 本期回款率 = 0;
                                if (sum4 > 0)
                                {
                                    本期回款率 = sum3 / sum4;
                                }

                                @((本期回款率 - 同期回款率).ToString("p2"))
                            }
                        else if (property.ColumnName == "序号")
                            {
                                @:合计
                            }
                            else
                            {
                                @:--
                            }

                        </td>
                    }
                }

            </tr>
        </FooterTemplate>
    </Table>
@* </div> *@
@code {
    private string username;

    [Inject]
    [NotNull]
    private ITableExport? TableExport { get; set; }
    [Inject]
    [NotNull]
    private ToastService? Toast { get; set; }

    private List<View_Custom> View_CustomList = new List<View_Custom>();
    private List<View_Depart> View_DepartList = new List<View_Depart>();

    private DateTimeRangeValue NormalDateTimeRangeValue { get; set; } = new();



    private IEnumerable<SelectedItem> 客户列表Items => View_CustomList.Select(i => new SelectedItem(i.cCusCode!, i.cCusName!)).ToList();
    private IEnumerable<SelectedItem> 部门Items => View_DepartList.Select(i => new SelectedItem(i.cDepCode!, i.cDepName!)).ToList();


    private SelectedItem? 选中客户 { get; set; }
    private IEnumerable<string> 选中部门List { get; set; }
    private string 选中部门InStr = "";

    private List<View_CustomPerson> View_CustomPersonList = new List<View_CustomPerson>();
    private IEnumerable<string> 选中业务员List { get; set; }
    private string 选中业务员InStr = "";
    private IEnumerable<SelectedItem> 业务员Items => View_CustomPersonList.Select(i => new SelectedItem(i.cCusPPerson!, i.cPersonName!)).ToList();

    private List<View_Custom> view_Customs = new List<View_Custom>();
    private SelectedItem? 选中养殖类别 { get; set; }
    private IEnumerable<SelectedItem> 养殖类别Items => view_Customs.Select(i => new SelectedItem(i.养殖类别!, i.养殖类别!)).ToList();


    [NotNull]
    private DataTableDynamicContext? DataTableDynamicContext { get; set; }

    protected override async void OnInitialized()
    {
        var authState = await authenticationStateProvider.GetAuthenticationStateAsync();
        var user = authState.User;
        username = user.Identity.Name;
        //今年1月1日
        NormalDateTimeRangeValue.Start = new DateTime(DateTime.Now.Year, 1, 1);
        //今天
        NormalDateTimeRangeValue.End = DateTime.Now.AddDays(-1);

        View_CustomList = _SqlSugarScope.Queryable<View_Custom>().ToList();
        //加一个请选择
        View_CustomList.Insert(0, new View_Custom { cCusCode = "", cCusName = "请选择" });

        //读取配置文件
        UserDataAuth userDataAuth = _SqlSugarScope.Queryable<UserDataAuth>().Where(it => it.UserName == username).First();
        List<Guid> guids = userDataAuth.CanViewDepart.Split(",").ToList().Select(it => Guid.Parse(it)).ToList();
        List<Sys_Department> depts = _SqlSugarScope.Queryable<Sys_Department>().Where(it => guids.Contains(it.DepartmentId)).ToList();
        List<string> deptNames = depts.Select(it => it.DepartmentName).ToList();
        var PaiChuBuMen = _congifuration.GetSection("PaiChuBuMen").Value;
        List<View_Depart> deptss = _SqlSugarScope.Queryable<View_Depart>().Where($"cDepCode not in ({PaiChuBuMen})").ToList();
        View_DepartList = deptss.Where(it => deptNames.Contains(it.cDepName)).ToList();
        //读取业务员配置文件
        var PaiChuYeWuYuan = _congifuration.GetSection("PaiChuYeWuYuan").Value;
        string sql = $"select distinct cPersonName,cCusPPerson from View_CustomPerson where cCusPPerson not in ({PaiChuYeWuYuan})";
        View_CustomPersonList = _SqlSugarScope.Ado.SqlQuery<View_CustomPerson>(sql);

        List<View_Custom> cus = _SqlSugarScope.Queryable<View_Custom>().Where(it => !string.IsNullOrEmpty(it.养殖类别)).Distinct().Select(it => new View_Custom { 养殖类别 = it.养殖类别 }).ToList();
        view_Customs = cus;
        view_Customs.Insert(0, new View_Custom { 养殖类别 = "请选择" });
        view_Customs.Add(new View_Custom { 养殖类别 = "非小棚虾" });
    }
    private Task OnNormalConfirm(DateTimeRangeValue value)
    {
        NormalLogger.LogDebug($"选择的时间范围是: {value.Start:yyyy-MM-dd HH:mm:ss} - {value.End:yyyy-MM-dd HH:mm:ss}");
        //遍历输出选中的客户
        if (选中客户 != null)
        {
            NormalLogger.LogDebug($"选中的客户是: {选中客户.Text}");
        }
        //遍历输出选中的部门
        if (选中部门List != null)
        {
            foreach (var item in 选中部门List)
            {

            }
        }
        return Task.CompletedTask;
    }
    private IEnumerable<SelectedItem> OnSearchTextChanged(string searchText)
    {
        return View_CustomList.Where(i => i.cCusName!.Contains(searchText, StringComparison.OrdinalIgnoreCase)).Select(i => new SelectedItem(i.cCusCode!, i.cCusName!));
    }

    private Task 部门选择改变事件(IEnumerable<SelectedItem> items)
    {
        选中部门InStr = string.Join("','", items.Select(it => it.Text).ToArray());
        return Task.CompletedTask;
    }
    private Task 业务员选择改变事件(IEnumerable<SelectedItem> items)
    {
        选中业务员InStr = string.Join("','", items.Select(it => it.Text).ToArray());
        return Task.CompletedTask;
    }
    private async Task<bool> OnExportAsync(ITableExportDataContext<DynamicObject> context)
    {
        // 导出符合条件的所有数据 data
        var ret = await TableExport.ExportExcelAsync(DataTableDynamicContext.GetItems(), context.Columns, $"Test_{DateTime.Now:yyyyMMddHHmmss}.xlsx");

        // 返回 true 时自动弹出提示框
        // await ShowToast(ret);
        return ret;
    }

    private async void Button_daochu(MouseEventArgs e)
    {
        //复制一个table用来导出
        DataTable dt = DataTableDynamicContext.DataTable.Copy();
        //增加一行合计
        DataRow dr = dt.NewRow();
        dr["本期销售额"] = dt.AsEnumerable().Sum(dr =>
                                {
                                    if (dr.IsNull("本期销售额")) return 0m;
                                    object value = dr["本期销售额"];
                                    if (value is int)
                                        return (decimal)(int)value;
                                    else if (value is decimal)
                                        return (decimal)value;
                                    else
                                        return 0m;
                                });

        dr["同期销售额"] = dt.AsEnumerable().Sum(dr =>
                                       {
                                           if (dr.IsNull("同期销售额")) return 0m;
                                           object value = dr["同期销售额"];
                                           if (value is int)
                                               return (decimal)(int)value;
                                           else if (value is decimal)
                                               return (decimal)value;
                                           else
                                               return 0m;
                                       });

        dr["本期回款额"] = dt.AsEnumerable().Sum(dr =>
                                               {
                                                   if (dr.IsNull("本期回款额")) return 0m;
                                                   object value = dr["本期回款额"];
                                                   if (value is int)
                                                       return (decimal)(int)value;
                                                   else if (value is decimal)
                                                       return (decimal)value;
                                                   else
                                                       return 0m;
                                               });
        dr["同期回款额"] = dt.AsEnumerable().Sum(dr =>
                                               {
                                                   if (dr.IsNull("同期回款额")) return 0m;
                                                   object value = dr["同期回款额"];
                                                   if (value is int)
                                                       return (decimal)(int)value;
                                                   else if (value is decimal)
                                                       return (decimal)value;
                                                   else
                                                       return 0m;
                                               });
        dr["销售差异"] = dt.AsEnumerable().Sum(dr =>
        {
            if (dr.IsNull("销售差异")) return 0m;
            object value = dr["销售差异"];
            if (value is int)
                return (decimal)(int)value;
            else if (value is decimal)
                return (decimal)value;
            else
                return 0m;
        });
        dr["回款差异"] = dt.AsEnumerable().Sum(dr =>
           {
               if (dr.IsNull("回款差异")) return 0m;
               object value = dr["回款差异"];
               if (value is int)
                   return (decimal)(int)value;
               else if (value is decimal)
                   return (decimal)value;
               else
                   return 0m;
           });

        dr["本期回款率"] = (decimal)dr["本期回款额"]/ (decimal)dr["本期销售额"];
        dr["同期回款率"] = (decimal)dr["同期回款额"] / (decimal)dr["同期销售额"];
        dr["回款率差异"] = (decimal)dr["本期回款率"] - (decimal)dr["同期回款率"];
        dt.Rows.Add(dr);
        DataTableDynamicContext dataTable = new DataTableDynamicContext(dt);
        var ret = await TableExport.ExportExcelAsync(dataTable.GetItems(), DataTableDynamicContext.GetColumns(), $"业务员发货排名表_{DateTime.Now:yyyyMMddHHmmss}.xlsx");
        // 导出符合条件的所有数据 data
        // var ret = await TableExport.ExportExcelAsync(DataTableDynamicContext.GetItems(), DataTableDynamicContext.GetColumns(), $"业务员发货排名_{DateTime.Now:yyyyMMddHHmmss}.xlsx");
        ToastService.Success("提示", "导出成功");
    }

    private string OnSort(string sortName, SortOrder sortOrder)
    {

        string sortString = "";
        if (sortOrder == SortOrder.Asc)
        {
            sortString = $"{sortName} asc";
        }
        else if (sortOrder == SortOrder.Desc)
        {
            sortString = $"{sortName} desc";
        }
        else
        {
            sortString = $"{sortName}";
        }
        DataTable sortTable = DataTableDynamicContext.DataTable.Clone();

        DataView dv = DataTableDynamicContext.DataTable.DefaultView;
        dv.Sort = sortString;
        sortTable = dv.ToTable();
        显示数据(sortTable);
        return sortString;
    }

    private decimal sum1;
    private decimal sum2;
    private decimal sum3;
    private decimal sum4;
    private decimal sum5;
    private decimal sum6;
    private decimal sum7;
    private decimal sum8;

    private async void Button_chaxun_Click(MouseEventArgs e)
    {
        sum1 = 0;
        sum2 = 0;
        sum3 = 0;
        sum4 = 0;
        sum5 = 0;
        sum6 = 0;
        sum7 = 0;
        sum8 = 0;
        //客户发货排名
        string sql;
        string 年度 = this.NormalDateTimeRangeValue.End.Year.ToString();
        string 今年开始日期 = this.NormalDateTimeRangeValue.Start.ToString("yyyy-MM-dd");
        string 今年结束日期 = this.NormalDateTimeRangeValue.End.ToString("yyyy-MM-dd");
        string 去年开始日期 = this.NormalDateTimeRangeValue.Start.AddYears(-1).ToString("yyyy-MM-dd");
        string 去年结束日期 = this.NormalDateTimeRangeValue.End.AddYears(-1).ToString("yyyy-MM-dd");
        string 去年 = 去年开始日期.Substring(0, 4);
        string 今年sql;
        string 去年sql;
        // string loginuser = username;
        string loginuser = "admin";
        sql = "SELECT DepartmentName FROM [netcoredev].[dbo].[View_PersonDepart] where  cPersonName='" + loginuser + "'";
        string depart = _SqlSugarScope.Ado.GetString(sql);

        string guid = Guid.NewGuid().ToString();  ///本次查询统一的
        if (string.IsNullOrEmpty(选中部门InStr) == true)
        {
            选中部门InStr += string.Join("','", View_DepartList.Select(it => it.cDepName));
        }
        string 部门清单 = "('" + 选中部门InStr + "')";

        sql = "select docyear, dbname FROM      Tset where docyear='" + 年度 + "'";
        DataTable tb1 = _SqlSugarScope.Ado.GetDataTable(sql);
        if (tb1.Rows.Count > 0)
        {
            今年sql = tb1.Rows[0]["dbname"].ToString();
            sql = "delete T客户发货 where usercode='" + loginuser + "'";
            _SqlSugarScope.Ado.ExecuteCommand(sql);
            //处理今年(今年sql)
            //1,塞入空客户
            #region
            sql = "insert into  T客户发货 (guid, usercode, Depart, cCusCode, cDLCode,irowno, cPersonCode,dDate ,";
            sql += " 本期销售额, 同期销售额)";
            sql += "select '" + guid + "','" + loginuser + "','" + depart + "', cCusCode ,cDLCode,irowno,cPersonCode,dDate,";
            sql += " iMoney,0 from View_发票明细 where 1=1 ";
            if (loginuser != "admin")
            {
                sql += " and cCusCode in (SELECT  cCusCode FROM View_CustomDepart where  cDepName='" + depart + "')";
                sql += " and cCusCode in (SELECT  cCusCode FROM TPersonCustom where cPersonName='" + loginuser + "')";
            }
            sql += " and period='" + 年度 + "' and dDate<='" + 今年结束日期 + "'and dDate>='" + 今年开始日期 + "'";
            _SqlSugarScope.Ado.ExecuteCommand(sql);
            sql = "insert into  T客户发货 (guid, usercode, Depart, cCusCode, cDLCode,irowno, cPersonCode,dDate ,";
            sql += " 本期销售额, 同期销售额)";
            sql += "select '" + guid + "','" + loginuser + "','" + depart + "', cCusCode ,cDLCode,irowno,cPersonCode,dDate,";
            sql += " 0,iMoney from View_发票明细 where 1=1 ";
            if (loginuser != "admin")
            {
                sql += " and cCusCode in (SELECT  cCusCode FROM View_CustomDepart where  cDepName='" + depart + "')";
                sql += " and cCusCode in (SELECT  cCusCode FROM TPersonCustom where cPersonName='" + loginuser + "')";
            }
            sql += " and period='" + 去年 + "' and dDate<='" + 去年结束日期 + "'and dDate>='" + 去年开始日期 + "'";
            _SqlSugarScope.Ado.ExecuteCommand(sql);
            #endregion


            //2塞入空客户
            #region
            sql = "delete T客户回款 where usercode='" + loginuser + "'";
            _SqlSugarScope.Ado.ExecuteCommand(sql);
            sql = "insert into  T客户回款 (guid, usercode,  Depart, cCusCode, iid, id, cPersonCode,dDate,  本期回款额, 同期回款额)";
            sql += "select '" + guid + "','" + loginuser + "','" + depart + "', cDwCode ,iID,id,cPerson,dDate,";
            sql += " iRAmt,0 from View_收款明细 where 1=1 ";
            if (loginuser != "admin")
            {
                sql += " and cDwCode in (SELECT  cCusCode FROM View_CustomDepart where  cDepName='" + depart + "')";
                sql += " and cDwCode in (SELECT  cCusCode FROM TPersonCustom where cPersonName='" + loginuser + "')";
            }
            sql += " and period='" + 年度 + "' and dDate<='" + 今年结束日期 + "'and dDate>='" + 今年开始日期 + "'";
            _SqlSugarScope.Ado.ExecuteCommand(sql);
            sql = "insert into  T客户回款 (guid, usercode,  Depart, cCusCode, iid, id, cPersonCode,dDate,  本期回款额, 同期回款额)";
            sql += "select '" + guid + "','" + loginuser + "','" + depart + "', cDwCode ,iID,id,cPerson,dDate,";
            sql += " 0,iRAmt from View_收款明细 where 1=1 ";
            if (loginuser != "admin")
            {
                sql += " and cDwCode in (SELECT  cCusCode FROM View_CustomDepart where  cDepName='" + depart + "')";
                sql += " and cDwCode in (SELECT  cCusCode FROM TPersonCustom where cPersonName='" + loginuser + "')";
            }
            sql += " and period='" + 去年 + "' and dDate<='" + 去年结束日期 + "'and dDate>='" + 去年开始日期 + "'";
            _SqlSugarScope.Ado.ExecuteCommand(sql);
            #endregion


            //更新客户
            sql = "update  a set a.代理商名称=b.cCusName,a.cPersonCode=b.cCusPPerson,a.销售员=b.cPersonName ";
            sql += " from T客户发货 a, View_CustomPerson b where a.cCusCode=b.cCusCode and a.guid='" + guid + "'";
            _SqlSugarScope.Ado.ExecuteCommand(sql);

            //更新部门
            sql = "update  a set a.部门=b.DepartmentName ";
            sql += " from T客户发货 a, View_PersonDepart b where a.cPersonCode=b.cPersonCode and a.guid='" + guid + "'";
            _SqlSugarScope.Ado.ExecuteCommand(sql);
            //更新客户
            sql = "update  a set a.代理商名称=b.cCusName,a.cPersonCode=b.cCusPPerson,a.销售员=b.cPersonName ";
            sql += " from T客户回款 a, View_CustomPerson b where a.cCusCode=b.cCusCode and a.guid='" + guid + "'";
            _SqlSugarScope.Ado.ExecuteCommand(sql);

            //更新部门
            sql = "update  a set a.部门=b.DepartmentName ";
            sql += " from T客户回款 a, View_PersonDepart b where a.cPersonCode=b.cPersonCode and a.guid='" + guid + "'";
            _SqlSugarScope.Ado.ExecuteCommand(sql);

            //养殖类别
            sql = "update  a set a.养殖类别=b.养殖类别 ";
            sql += " from T客户发货 a, View_Custom b where  a.cCusCode=b.cCusCode and a.guid='" + guid + "'";
            _SqlSugarScope.Ado.ExecuteCommand(sql);
            //养殖类别
            sql = "update  a set a.养殖类别=b.养殖类别 ";
            sql += " from T客户回款 a, View_Custom b where  a.cCusCode=b.cCusCode and a.guid='" + guid + "'";
            _SqlSugarScope.Ado.ExecuteCommand(sql);

            //显示数据
            sql = @"select  
                t.销售员,t.部门,Convert(decimal(18,4),sum(本期销售)/10000) 本期销售额, Convert(decimal(18,4),sum(同期销售)/10000) 同期销售额 ,
                Convert(decimal(18,4),sum(本期回款)/10000) [本期回款额],Convert(decimal(18,4),sum(同期回款)/10000) [同期回款额],
                Convert(decimal(18,4),(sum(本期销售)-sum(同期销售))/10000) 销售差异,0.00 销售差异率,Convert(decimal(18,4),(sum(本期回款)-sum(同期回款) )/10000) 回款差异,
                0.00 回款率差异,0.00 本期回款率,0.00 同期回款率
                from (SELECT  销售员,部门, sum(本期销售额) 本期销售, sum(同期销售额) 同期销售 ,0 本期回款 ,0 同期回款
                FROM T客户发货 where guid='" + guid + "'";
            if (string.IsNullOrEmpty(this.选中客户?.Text) == false && this.选中客户?.Text != "请选择")
            {
                sql += " and 代理商名称 like '%" + this.选中客户.Text.Trim().Replace("-", "") + "%'";
            }
            if (this.选中养殖类别?.Text != "请选择" && this.选中养殖类别?.Text != "非小棚虾")
            {
                sql += " and 养殖类别='" + this.选中养殖类别.Text + "'";
            }
            if (this.选中养殖类别?.Text != "请选择" && this.选中养殖类别?.Text == "非小棚虾")
            {
                sql += " and 养殖类别 is null";
            }

            sql += " and 部门 in " + 部门清单;
            sql += " group by 部门, 销售员 ";
            sql += @" union all
                SELECT  销售员,部门, 0 本期销售, 0 同期销售 ,sum([本期回款额]) 本期回款 ,sum([同期回款额]) 同期回款
                FROM [T客户回款] where guid='" + guid + "'";
            if (string.IsNullOrEmpty(this.选中客户?.Text) == false && this.选中客户?.Text != "请选择")
            {
                sql += " and 代理商名称 like '%" + this.选中客户.Text.Trim().Replace("-", "") + "%'";
            }
            if (this.选中养殖类别?.Text != "请选择" && this.选中养殖类别?.Text != "非小棚虾")
            {
                sql += " and 养殖类别='" + this.选中养殖类别.Text + "'";
            }
            if (this.选中养殖类别?.Text != "请选择" && this.选中养殖类别?.Text == "非小棚虾")
            {
                sql += " and 养殖类别 is null";
            }

            sql += " and 部门 in " + 部门清单;
            sql += " group by 部门, 销售员)  t group by 部门, 销售员";
            DataTable dataTableHZ = _SqlSugarScope.Ado.GetDataTable(sql);
            if (dataTableHZ != null)
            {

                for (int i = 0; i < dataTableHZ.Rows.Count; i++)
                {
                    DataRow dr = dataTableHZ.Rows[i];
                    decimal 本同期回款率差异 = 0;
                    decimal 本期回款率 = 0;
                    decimal 同期回款率 = 0;
                    decimal 销售差异率 = 0;
                    if (decimal.TryParse(dr["本期销售额"].ToString(), out decimal result) == true && result != 0)
                    {
                        // decimal a = Pub.ToDecimal(dr["本期回款额"].ToString());
                        // decimal b = Pub.ToDecimal(dr["本期销售额"].ToString());
                        decimal.TryParse(dr["本期回款额"].ToString(), out decimal a);
                        decimal.TryParse(dr["本期销售额"].ToString(), out decimal b);
                        本期回款率 = (a  / b);
                        dataTableHZ.Rows[i]["本期回款率"] = 本期回款率;

                    }
                    else
                    {
                        本期回款率 = 0;
                    }
                    if (decimal.TryParse(dr["同期销售额"].ToString(), out decimal result2) == true && result2 != 0)
                    {
                        // decimal a = Pub.ToDecimal(dr["同期回款额"].ToString());
                        // decimal b = Pub.ToDecimal(dr["同期销售额"].ToString());
                        decimal.TryParse(dr["同期回款额"].ToString(), out decimal a);
                        decimal.TryParse(dr["同期销售额"].ToString(), out decimal b);
                        decimal.TryParse(dr["销售差异"].ToString(), out decimal 销售差异);
                        同期回款率 = (a  / b);
                        销售差异率 = (销售差异 / b);
                        dataTableHZ.Rows[i]["同期回款率"] = 同期回款率;
                        dataTableHZ.Rows[i]["销售差异率"] = 销售差异率;
                    }
                    else
                    {
                        同期回款率 = 0;

                    }
                    本同期回款率差异 = 本期回款率 - 同期回款率;
                    dataTableHZ.Rows[i]["回款率差异"] = 本同期回款率差异; ;


                }
            }
            sql = " delete T客户发货 where  guid='" + guid + "' ";
            sql += " delete T客户回款 where  guid='" + guid + "' ";
            _SqlSugarScope.Ado.ExecuteCommand(sql);
            显示数据(dataTableHZ);
            await ToastService.Information("提示", "查询成功");
        }
        else
        {
            await ToastService.Success("提示", "选择的日期有误", autoHide: true);
        }

    }

    public void 显示数据(DataTable dt)
    {
        //  UserDataAuth userDataAuth = _SqlSugarScope.Queryable<UserDataAuth>().Where(it => it.UserName == username).First();
        // List<Guid> guids = userDataAuth.CanViewDepart.Split(",").ToList().Select(it => Guid.Parse(it)).ToList();
        // List<Sys_Department> depts = _SqlSugarScope.Queryable<Sys_Department>().Where(it => guids.Contains(it.DepartmentId)).ToList();
        // List<string> deptNames = depts.Select(it => it.DepartmentName).ToList();

        if (dt != null && dt.Rows.Count > 0)
        {
           
            //修改列名
            if (dt.Columns.Contains("销售员"))
            {
                dt.Columns["销售员"].ColumnName = "业务员";
            }
            //找出对应选中的销售员
            if (选中业务员InStr != "")
            {
                dt = dt.Select("业务员 in ('" + 选中业务员InStr + "')").CopyToDataTable();
            }
            // //只能看到 deptNames 里的部门
            // dt = dt.Select("部门 in ('" + string.Join("','", deptNames) + "')").CopyToDataTable();

            //dt第一列插入序号列
            if (dt.Columns.Contains("序号") == false)
            {
                dt.Columns.Add("序号", typeof(int)).SetOrdinal(0);
            }
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dt.Rows[i]["序号"] = i + 1;
            }
        }
        DataTableDynamicContext = new DataTableDynamicContext(dt, (context, col) =>
            {
                //所有列可排序
                col.Sortable = true;
                col.DefaultSort = true;
                // col.TextWrap = true;
                if (col.GetFieldName() == "序号")
                {
                    col.Width = 40;
                }
                else if (col.GetFieldName() == "本期回款率" || col.GetFieldName() == "同期回款率" || col.GetFieldName() == "回款率差异" || col.GetFieldName() == "销售差异率")
                {
                    col.FormatString = "P2";
                    col.Width = 80;
                }
                else
                {
                    col.Width = 80;
                }
              
                
                // //如果列的类型是数字类型设置宽度120
                // if (Type.GetTypeCode(col.PropertyType) != TypeCode.String)
                // {
                //     col.Width = 120;
                // }
                // else
                // {
                //     col.Width = 150;
                // }
                
            });

        StateHasChanged();
    }
}
